# _*_ coding: utf-8 _*_
from __future__ import absolute_import, unicode_literals
from celery import shared_task  # 可以无需任何具体的应用程序实例创建任务
from fastrunner import models
from fastrunner.utils.loader import save_summary, debug_suite, debug_api
from fastrunner.utils.host import parse_host
from fastrunner.utils.email_send import send_result_email, prepare_email_content, control_email, parser_runresult, prepare_email_file, get_summary_report
from fastrunner.utils.parser import parse_config
from fastrunner.utils.dd_alarm import dd_alert
from FasterRunner.settings import logger


@shared_task
def async_debug_api(api, project, name, config=None):
    """异步执行api
    """
    logger.info("invoke async_debug_api:[api={},project={},name={},config={}]".format(api, project, name, config))
    summary = debug_api(api, project, config=config, save=False)
    save_summary(name, summary, project)
    logger.info("invoke async_debug_api end:")


@shared_task
def async_debug_test(test_case, project, name, report_name, config, test_data):
    """异步执行testcase
    """
    logger.info("invoke async_debug_test:[test_case={},project={},name={},report_name={},config={}, test_data={}]"
                .format(test_case, project, name, report_name, config, test_data))
    summary = debug_api(test_case, project, name=name, config=config, save=True, test_data=test_data)
    save_summary(report_name, summary, project)
    logger.info("invoke async_debug_test end:")


@shared_task
def async_debug_suite(suite, project, obj, report_name, config):
    """异步执行suite
    """
    summary = debug_suite(suite, project, obj, config=config, save=True)
    save_summary(report_name, summary, project)


@shared_task
def schedule_debug_suite(*args, **kwargs):
    """定时任务
    """
    project = int(kwargs["project"])

    sample_summary = []
    if not args:
        raise ValueError('任务列表为空，请检查')
    for cases in args:
        case_kwargs = cases.get('kwargs', '')
        test_list = models.CaseStep.objects.filter(case__id=cases["id"]).order_by("step").values("body")

        if not test_list:
            raise ValueError('用例缺失，请检查')
        report_name = cases["name"]
        case_name = cases["name"]
        project_id = cases.get('project')
        test_case = []
        test_data = None
        g_host_info = ''
        config_name = ''
        host_name = ''
        if case_kwargs:
            report_name = case_kwargs["testCaseName"]
            if case_kwargs.get("excelTreeData", []):
                test_data = tuple(case_kwargs["excelTreeData"])
            host_name = case_kwargs["hostInfo"]
            config_name = case_kwargs["currentConfig"]
        for content in test_list:
            body = eval(content["body"])
            test_case.append(parse_host(g_host_info, body))

        config = parse_config(project_id, host_name, config_name)
        summary = debug_api(test_case, project, name=case_name, config=parse_host(g_host_info, config), save=False, test_data=test_data)
        summary["name"] = report_name
        sample_summary.append(summary)

    if sample_summary:
        summary_report = get_summary_report(sample_summary)
        save_summary(kwargs["task_name"], summary_report, project, type=3)
        is_send_email = control_email(sample_summary, kwargs)
        if is_send_email:
            logger.info("is_send_email:true")
            sensitive_keys = kwargs.get('sensitive_keys', [])
            runresult = parser_runresult(sample_summary, sensitive_keys)
            peoject_name = models.Project.objects.get(id=project).name
            subject_name = peoject_name + ' - ' + kwargs["task_name"]
            if runresult["fail_task"] > 0:
                subject_name += " - 失败：" + ",".join([err_msg["proj"] for err_msg in runresult["error_list"]])
            else:
                subject_name += " - 成功！"
            html_conetnt = prepare_email_content(runresult, subject_name)
            send_file_path = prepare_email_file(summary_report)
            send_status = send_result_email(subject_name, kwargs["receiver"], kwargs["mail_cc"], send_html_content=html_conetnt, send_file_path=send_file_path)
            dd_alert(runresult)
            if send_status:
                print('邮件发送成功')
            else:
                print('邮件发送失败')
        else:
            logger.info("is_send_email:false")
